﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Top.PointStore
{
    public static class RedisHelper
    {
        private static Lazy<ConnectionMultiplexer> lazyMaster = new Lazy<ConnectionMultiplexer>(() =>
        {
            return ConnectionMultiplexer.Connect(Top.Core.Configs.AppSettings["MasterRedis"]);
        });

        /// <summary>
        /// 延时加载从
        /// </summary>
        private static Lazy<ConnectionMultiplexer> lazyRedis = new Lazy<ConnectionMultiplexer>(() =>
        {
            return ConnectionMultiplexer.Connect(Top.Core.Configs.AppSettings["SlaveRedis"]);
        });

        /// <summary>
        /// 主写
        /// </summary>
        public static ConnectionMultiplexer writeRedis
        {
            get
            {
                return lazyMaster.Value;
            }
        }

        /// <summary>
        /// 从读
        /// </summary>
        public static ConnectionMultiplexer readRedis
        {
            get
            {
                return lazyRedis.Value;
            }
        }

        #region Pub/Sub

        /// <summary>
        /// 订阅频道
        /// </summary>
        /// <param name="channel">频道</param>
        /// <param name="handler">回调</param>
        public static void Subscribe(string channel, Action<RedisChannel, RedisValue> handler)
        {
            ISubscriber sub = writeRedis.GetSubscriber();

            sub.SubscribeAsync(channel, handler);
        }

        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="channel">频道</param>
        /// <param name="message">消息</param>
        /// <returns></returns>
        public static async Task<long> Publish(string channel, string message)
        {
            ISubscriber sub = writeRedis.GetSubscriber();
            return await sub.PublishAsync(channel, message);

        }

        #endregion
    }
}
